import {each, get} from 'lodash'
import {getAllChannel} from "@/api/index"
import {getAllDict} from '@/api/dictionaryData'
import storage from './storage'
import moment from 'moment'
import { getVehicleTypeName } from './filter'
export default {
  trimValue(data, type) {
    each(data, (value, key) => {
      if (typeof (value) === 'string') data[key] = value.trim()
      if (typeof (value) === 'undefined' && type) data[key] = ''
      if (key.indexOf('Type') !== -1 && !value) data[key] = 0
    })
    return data
  },
  //把为零的字段置为空
  valueToNull(data) {
    each(data, (value, key) => {
      if (value === 0) data[key] = undefined
    })
    return data
  },
  phoneValidator(rule, value, callback) {
    const phone = value && value.trim()
    const isMobile = /^1[3|4|5|6|7|8|9]\d{9}$/
    const isZuoji = /^0\d{2,3}-?\d{7,8}$/
    const isZuoji2 = /\d{6,8}/
    if (!isMobile.test(phone) && !isZuoji.test(phone) && !isZuoji2.test(phone)) {
      callback(new Error('请输入正确的联系电话'))
    } else {
      callback()
    }
  },
  // 将时间戳转换为特定日期格式
  formatTimestamp(timestamp) {
    const date = new Date(timestamp); // 不需要将毫秒转换为秒，因为这个时间戳已经是以毫秒为单位的
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，需要加1
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },
  
  purePhoneValidator(rule, value, callback) {
    const phone = value && value.trim()
    const isMobile = /^1[3|4|5|6|7|8|9]\d{9}$/
    if (!isMobile.test(phone)) {
      callback(new Error('请输入正确的手机号码'))
    } else {
      callback()
    }
  },
  judgeTime(timeStr) {
    return timeStr !== '' && timeStr !== '0001-01-01 00:00:00'
  },
  formatHours(hours) {
    const days = parseInt(hours / 24)
	  const remainHours = parseInt(hours % 24)
	  if (days === 0) return remainHours + '小时'
	  return `${days}天${remainHours ? remainHours + '小时' : ''}`
  },
  getVehicleTypeName,
	getStartTime(time) {
		if (!time) return
		return moment(time).format('YYYY-MM-DD 00:00:00')
	},
	getEndTime(time) {
		if (!time) return
		return moment(time).format('YYYY-MM-DD 23:59:59')
	},
  formatEmptyTime(timeStr) {
    if (timeStr === '0001-01-01 00:00:00') return ''
    return timeStr
  },
  /**
   * 生成uuid
   * @returns {string}
   */
  uuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      let r = Math.random() * 16 | 0
      let v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  },
	globalResizeImg() {//图片缩放
	  return '?x-oss-process=image/resize,h_100,m_lfit'
	},
  //转化金额
  numberConversion(value) {
    value = value ? value : 0
    const newValue = ['', '', '']
    let fr = 1000
    let num = 3
    let txt = ''
    let fm = 1
    while (value / fr >= 1) {
      fr *= 10
      num += 1
    }
    if (num <= 5) { // 千
      newValue[0] = value + ''
      newValue[1] = ''
    } else if (num <= 8) { // 万
      txt = (parseInt(num - 4) / 3) > 1 ? '千万' : '万'
      fm = txt === '万' ? 10000 : 10000000
      if (value % fm === 0) {
        newValue[0] = parseInt(value / fm) + ''
      } else {
        newValue[0] = parseFloat(value / fm).toFixed(2) + ''
      }
      newValue[1] = txt
    } else if (num <= 16) { // 亿
      txt = (num - 8) / 3 > 1 ? '千亿' : '亿'
      txt = (num - 8) / 4 > 1 ? '万亿' : txt
      txt = (num - 8) / 7 > 1 ? '千万亿' : txt


      fm = 1
      if (txt === '亿') {
        fm = 100000000
      } else if (txt === '千亿') {
        fm = 100000000000
      } else if (txt === '万亿') {
        fm = 1000000000000
      } else if (txt === '千万亿') {
        fm = 1000000000000000
      }
      if (value % fm === 0) {
        newValue[0] = parseInt(value / fm) + ''
      } else {
        newValue[0] = parseFloat(value / fm).toFixed(2) + ''
      }
      newValue[1] = txt
    }
    if (value < 1000) {
      newValue[0] = value + ''
      newValue[1] = ''
    }
    return newValue.join('')
  },
  // 渠道
  getChannel() {
    return new Promise((resolve, reject) => {
      getAllChannel().then(res => {
        resolve(res)
      }).catch((err) => {
        reject(err)
      })
    })
  },
  getAllDict() {
    return new Promise((resolve, reject) => {
      const dictList = storage.get('dictList')
      if (!dictList) {
        getAllDict().then(data => {
          storage.set('dictList', data, +new Date() + 24 * 60 * 1000)
          resolve(data)
        }).catch(reject)
      } else {
        resolve(dictList)
      }
    })
  },
  //数据字典
  async getDictList(categoryCode) {
    const dictList = await this.getAllDict()
    return get(dictList.find(e => e.categoryCode === categoryCode), 'dictList') || []
  },
  
  getEnumName(enumList, value) {
    const currEnum = enumList.find(e => e.value === value)
    return currEnum && currEnum.name
  },
  getPointsCenter(points) {
    let point_num = points.length; //坐标点个数
    let X = 0, Y = 0, Z = 0;
    for (let i = 0; i < points.length; i++) {
      if (points[i].length == 0) {
        continue;
      }
      let point = points[i]
      let lat, lng, x, y, z;
      lng = parseFloat(point[0]) * Math.PI / 180;
      lat = parseFloat(point[1]) * Math.PI / 180;
      x = Math.cos(lat) * Math.cos(lng);
      y = Math.cos(lat) * Math.sin(lng);
      z = Math.sin(lat);
      X += x;
      Y += y;
      Z += z;
    }
    X = X / point_num;
    Y = Y / point_num;
    Z = Z / point_num;
    let tmp_lng = Math.atan2(Y, X);
    let tmp_lat = Math.atan2(Z, Math.sqrt(X * X + Y * Y));
    return [ tmp_lng * 180 / Math.PI, tmp_lat * 180 / Math.PI];
  }
}
